<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "mkt_follow".
 *
 * @property string $id
 * @property string $user_id
 * @property string $follow_id
 * @property string $create_time
 */
class MktFollow extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'mkt_follow';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['user_id', 'follow_id'], 'integer'],
            [['create_time'], 'safe'],
            [['user_id', 'follow_id'], 'unique', 'targetAttribute' => ['user_id', 'follow_id'], 'message' => '此人已被关注']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'user_id' => '我',
            'follow_id' => '被我关注的人',
            'create_time' => '关注时间',
        ];
    }

    public function behaviors() {
        return [
            [
                'class' => \yii\behaviors\TimestampBehavior::className(),
                'createdAtAttribute' => 'create_time',
                'updatedAtAttribute' => 'create_time',
                'value' => new \yii\db\Expression('NOW()'),
            ],
        ];
    }

    /**
     * @inheritdoc
     * @return MktFollowQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new MktFollowQuery(get_called_class());
    }

    public function getUser()
    {
        return $this->hasOne(MktUser::className(), ['id' => 'user_id']);
    }

    public function getFollowUser()
    {
        return $this->hasOne(MktUser::className(), ['id' => 'follow_id']);
    }



    public static function followAjax($user_id, $follow_id) {

        $follow = self::findOne(['user_id' => $user_id, 'follow_id' => $follow_id]);
        if(empty($follow))
        {
            //follow
            $follow = new self;
            $follow->user_id = $user_id;
            $follow->follow_id = $follow_id;

            $follow->save(false);
            return json_encode(['code' => 0 , 'msg' => 'follow ok!']);
        }
        else
        {
            //dis-follow
            $follow->delete(); 
            return json_encode(['code' => -1 , 'msg' => 'dis-follow!']);
        }
        
    }

    /*
    public static function deleteFollowAjax($params)
    {
        yii::error(print_r([$_GET, $params], true));
        $model = MktChat::findOne($params['id']);
        $model->approved = MktChat::APPROVE_STATUS_IGNORE;
        $result = $model->save();
        if ( true !== $result) {
            yii::error($result);
            return \yii\helpers\Json::encode(['code' => 1, 'data' => $result]);
        }
        return \yii\helpers\Json::encode(['code' => 0, 'data' => 'OK']);
    }

    */
}
